package com.tangding.commons;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.session.ExpiredSessionException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.base.Strings;
import com.tangding.common.exception.GException;
import com.tangding.common.logx.LogHelp;
import com.tangding.common.tools.ErrorConstants;
import com.tangding.pojo.response.MessageDto;

/**
 * @description 异常处理中心
 *
 * @author Ranger
 * @version 2017年7月12日_下午1:59:46
 *
 */
@ControllerAdvice
public class ExceptionUniHandler {
	
    @ResponseBody
    @ExceptionHandler(GException.class)
	MessageDto handGException(GException e) {
		MessageDto result = new MessageDto();
		result.setCode(e.getErr());
		if (Strings.isNullOrEmpty(e.getMsg())) {
			result.setMsg(ErrorConstants.getDesc(e.getErr()));
		}else {
			result.setMsg(e.getMsg());
		}
		LogHelp.doLogAppErr(e);
		return result;
	}
    
	@ResponseBody
	@ExceptionHandler(Exception.class)
	MessageDto handException(Exception e) {
		MessageDto result = new MessageDto();
		result.setCode(ErrorConstants.FAIL);
		result.setMsg(e.getMessage());
		LogHelp.doLogException(e);
		return result;
	}
	
	@ResponseBody
	@ExceptionHandler(AuthorizationException.class)
	ModelAndView handleAuthorizationException(AuthorizationException e) {
		ModelAndView view = new ModelAndView();
		view.setViewName("redirect:/login");
		LogHelp.doLogException(e);
		return view;
	}
	
	@ResponseBody
	@ExceptionHandler(ExpiredSessionException.class)
	ModelAndView handleExpiredSessionException(ExpiredSessionException e) {
		ModelAndView view = new ModelAndView();
		view.setViewName("redirect:/login");
		LogHelp.doLogException(e);
		return view;
	}
	
	
	@ResponseBody
	@ExceptionHandler(AuthenticationException.class)
	ModelAndView handleAuthenticationException(AuthenticationException e) {
		ModelAndView view = new ModelAndView();
		view.setViewName("redirect:/login");
		LogHelp.doLogException(e);
		return view;
	}
}